package com.yonyou.crm.sys.modules.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yonyou.crm.common.biz.service.BaseBizServiceImpl;
import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.sys.modules.entity.ApiVO;

@Service
public class ApiBizServiceImpl extends BaseBizServiceImpl<ApiVO>{
	
	/**
	 * 获取API对象
	 * 
	 * @return
	 */
	public ApiVO getApi(Long id) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);

		List<ApiVO> apiList = new ArrayList<ApiVO>();
		apiList = dao.selectVoList(ApiVO.class, "ListApi", paramMap);
		if (apiList.size()>0) {
			ApiVO apiVO = apiList.get(0);
			handleFields(apiVO);
			return apiVO;
		} else {
			throw new CrmBusinessException("API不存在");
		}
	}
	
	private void handleFields(ApiVO apiVO) {

		// 处理API字段，API上的字段形式为{field}
		String api = apiVO.getApi();
		String patterStr = "\\{.*?\\}";
		Matcher matcher = Pattern.compile(patterStr).matcher(api);
		String[] apiURLSubstituteFields = null;
		while (matcher.find()) {
			String field = StringUtils.trimLeadingCharacter(matcher.group(), '{');
			field = StringUtils.trimTrailingCharacter(field, '}');
			apiURLSubstituteFields = StringUtils.addStringToArray(apiURLSubstituteFields,field );
		}
		apiVO.setApiURLSubstituteFields(apiURLSubstituteFields);
		// 处理过滤条件字段
		String filterFieldsString = apiVO.getFilterFieldsStr();
		if (filterFieldsString.length()>0) {
			String[] filterFields = StringUtils.delimitedListToStringArray(filterFieldsString, ",");
			apiVO.setFilterFields(filterFields);
		}
	}
	
}



